package com.example.wan_android.ui.activity

import android.content.ComponentName
import android.content.Intent
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.example.wan_android.viewmodel.BaseViewModel

abstract class BaseActivity<V : ViewDataBinding, VM : BaseViewModel>(
    private val vmClass: Class<VM>,
    private val layoutId: Int,
    private val viewModelId: Int
) : AppCompatActivity() {
    protected var mViewDataBinding: V? = null
    protected var mViewModel: VM? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(layoutId)
        mViewDataBinding = DataBindingUtil.setContentView(this, layoutId)
        mViewModel = ViewModelProvider(this)[vmClass]
        if (viewModelId != 0) {
            mViewDataBinding?.setVariable(viewModelId, mViewModel)
        }
        mViewDataBinding?.lifecycleOwner = this
        initView()
        initActJumpData()
    }

    private fun initActJumpData() {
        if (mViewModel?.actJumpLiveData?.hasObservers() == true) {
            return
        }
        mViewModel?.actJumpLiveData?.observe(this) { data ->
            if (data.isDeprecated) {
                return@observe
            }
            data.targetClass?.let {
                (data.targetIntent ?: Intent()).apply {
                    component = ComponentName(this@BaseActivity, it)
                }.also {
                    startActivity(it)
                }
            }
            if (data.finishCurrent) {
                data.activityResult?.let {
                    setResult(it.resultCode, it.data)
                }
                finish()
            }
            data.isDeprecated = true
        }
    }

    abstract fun initView()
}